<template>
  <div class="product-detail-container">
    <!-- 顶部导航栏 -->
    <div class="product-detail-header">
      <router-link to="/" class="back-button">
        <el-icon><arrow-left /></el-icon>
返回
      </router-link>
    </div>

    <!-- 主要内容区 -->
    <div class="product-detail-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <el-alert :title="error" type="error" show-icon />
      </div>

      <div v-else-if="product" class="product-info">
        <!-- 商品图片区域 -->
        <div class="product-images">
          <div class="main-image">
            <img :src="product.imageUrl" alt="{{ product.name }}" />
          </div>
          <div class="thumbnail-list">
            <div 
              v-for="(image, index) in product.images || [product.imageUrl]" 
              :key="index"
              class="thumbnail"
              :class="{ active: currentThumbnail === index }"
              @click="currentThumbnail = index"
            >
              <img :src="image" alt="{{ product.name }} 缩略图 {{ index + 1 }}" />
            </div>
          </div>
        </div>

        <!-- 商品基本信息 -->
        <div class="product-basic-info">
          <h1 class="product-name">{{ product.name }}</h1>
          <div class="product-price">
            <span class="price-label">价格:</span>
            <span class="price-value">¥{{ formatPrice(product.price) }}</span>
          </div>
          <div class="product-stock">
            <span class="stock-label">库存:</span>
            <span class="stock-value">{{ product.stock }} 件</span>
          </div>
          <div class="product-rating">
            <el-rate 
              :value="product.rating || 0" 
              disabled 
              :max="5" 
              show-score 
              text-color="#ff9900"
            />
          </div>
          <div class="product-sales">
            <span class="sales-label">销量:</span>
            <span class="sales-value">{{ product.sales || 0 }} 件</span>
          </div>

          <!-- 商品规格选择 -->
          <div v-if="product.specifications && product.specifications.length > 0" class="product-specs">
            <h3 class="specs-title">选择规格:</h3>
            <div v-for="(spec, index) in product.specifications" :key="index" class="spec-group">
              <span class="spec-name">{{ spec.name }}:</span>
              <div class="spec-options">
                <span 
                  v-for="(option, optIndex) in spec.options" 
                  :key="optIndex"
                  class="spec-option"
                  :class="{ active: selectedSpecs[spec.name] === option }"
                  @click="selectSpec(spec.name, option)"
                >
                  {{ option }}
                </span>
              </div>
            </div>
          </div>

          <!-- 购买数量选择 -->
          <div class="quantity-selector">
            <span class="quantity-label">数量:</span>
            <div class="quantity-controls">
              <button class="quantity-btn minus" @click="decreaseQuantity" :disabled="quantity <= 1">
                -
              </button>
              <input type="number" v-model.number="quantity" min="1" :max="product.stock" />
              <button class="quantity-btn plus" @click="increaseQuantity" :disabled="quantity >= product.stock">
                +
              </button>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" size="large" @click="addToCart" :disabled="!canAddToCart">
              <el-icon><shopping-cart /></el-icon>
              加入购物车
            </el-button>
            <el-button type="success" size="large" @click="buyNow" :disabled="!canAddToCart">
              <el-icon><ticket /></el-icon>
              立即购买
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品详情标签页 -->
    <div v-if="product && !loading && !error" class="product-detail-tabs">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="商品详情" name="details">
          <div class="product-description" v-html="product.description" />
        </el-tab-pane>
        <el-tab-pane label="用户评价" name="reviews">
          <div v-if="reviews.length > 0" class="reviews-container">
            <div v-for="review in reviews" :key="review.id" class="review-item">
              <div class="review-header">
                <span class="reviewer-name">{{ review.userName }}</span>
                <el-rate :value="review.rating" disabled :max="5" />
                <span class="review-date">{{ formatDate(review.createdAt) }}</span>
              </div>
              <div class="review-content">{{ review.content }}</div>
              <div v-if="review.images && review.images.length > 0" class="review-images">
                <img v-for="(img, index) in review.images" :key="index" :src="img" class="review-image" />
              </div>
            </div>
          </div>
          <div v-else class="no-reviews">
            暂无评价
          </div>
        </el-tab-pane>
        <el-tab-pane label="售后服务" name="service">
          <div class="service-info">
            <ul>
              <li>支持7天无理由退换货</li>
              <li>全国联保，享受三包服务</li>
              <li>商品质量问题，15天内可更换</li>
              <li>具体服务政策以商品页面为准</li>
            </ul>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 推荐商品 -->
    <div v-if="relatedProducts && relatedProducts.length > 0" class="related-products">
      <h2 class="related-title">猜你喜欢</h2>
      <div class="related-list">
        <div 
          v-for="relatedProduct in relatedProducts" 
          :key="relatedProduct.id"
          class="related-item"
          @click="navigateToProduct(relatedProduct.id)"
        >
          <img :src="relatedProduct.imageUrl" alt="{{ relatedProduct.name }}" class="related-image" />
          <h3 class="related-name">{{ relatedProduct.name }}</h3>
          <span class="related-price">¥{{ formatPrice(relatedProduct.price) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { Product, ProductReview, ProductSpecification } from '../../types/product';
import { productService } from '../../api/productService';
import { addToCart as addToCartApi } from '../../api/cartService';
import { ArrowLeft, ShoppingCart, Ticket } from '@element-plus/icons-vue';

// 路由相关
const router = useRouter();
const route = useRoute();
const productId = route.params.id as string;

// 响应式数据
const product = ref<Product | null>(null);
const reviews = ref<ProductReview[]>([]);
const relatedProducts = ref<Product[]>([]);
const loading = ref(true);
const error = ref('');
const currentThumbnail = ref(0);
const quantity = ref(1);
const selectedSpecs = ref<Record<string, string>>({});
const activeTab = ref('details');

// 计算属性
const canAddToCart = computed(() => {
  if (!product.value || product.value.stock <= 0) return false;
  
  // 检查是否所有规格都已选择
  if (product.value.specifications && product.value.specifications.length > 0) {
    return product.value.specifications.every((spec: { name: string }) => 
      selectedSpecs.value.hasOwnProperty(spec.name) && selectedSpecs.value[spec.name]
    );
  }
  
  return true;
});

// 方法
const navigateToProduct = (id: string) => {
  router.push(`/product/${id}`);
};

const selectSpec = (specName: string, option: string) => {
  selectedSpecs.value[specName] = option;
};

const increaseQuantity = () => {
  if (product.value && quantity.value < product.value.stock) {
    quantity.value++;
  }
};

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 在script setup的顶部添加导入
import { useAuthStore } from '@/stores/auth';

// 在script setup中添加authStore实例
const authStore = useAuthStore();

// 修改addToCart方法，添加登录检查
const addToCart = async () => {
  if (!canAddToCart.value || !product.value) return;
  
  // 检查用户是否已登录
  if (!authStore.isAuthenticated) {
    // 保存当前页面信息，以便登录后返回
    localStorage.setItem('redirectAfterLogin', window.location.pathname);
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  try {
    await addToCartApi({
      productId: Number(product.value.id),
      quantity: quantity.value
    });
    ElMessage.success('成功加入购物车');
  } catch (err) {
    ElMessage.error('加入购物车失败，请重试');
  }
};

const buyNow = () => {
  if (!canAddToCart.value || !product.value) return;
  
  // 可以直接跳转到订单确认页面
  router.push({
    path: '/checkout',
    query: {
      productId: product.value.id,
      quantity: quantity.value.toString()
    }
  });
};

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 添加一个格式化价格的辅助函数
const formatPrice = (price: string | number | undefined): string => {
  // 处理undefined或null情况
  if (price === undefined || price === null) {
    return '0.00';
  }
  
  // 转换为数字
  const numPrice = typeof price === 'string' ? parseFloat(price) : price;
  
  // 检查是否为有效数字
  if (isNaN(numPrice)) {
    return '0.00';
  }
  
  return numPrice.toFixed(2);
};

// 初始化数据
const fetchProductDetail = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await productService.getProduct(Number(productId));
    
    // 明确处理响应数据结构
    if (response && typeof response === 'object') {
      // 如果数据包含嵌套的 product 字段，则使用它，否则直接使用 response.data
      product.value = (response as any).product || response.data as Product;
      reviews.value = (response as any).reviews || [];
    } else {
      throw new Error('Invalid response format');
    }
    
    // 初始化规格选择（如果有）
    if (product.value?.specifications && product.value.specifications.length > 0) {
      product.value.specifications.forEach((spec: { name: string, options: string[] }) => {
        if (spec.options && spec.options.length > 0) {
          selectedSpecs.value[spec.name] = spec.options[0] || '';
        }
      });
    }
  } catch (err) {
    error.value = '获取商品详情失败';
    console.error('Failed to fetch product detail:', err);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchProductDetail();
});
</script>

<style scoped>
.product-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.product-detail-header {
  padding: 16px 20px;
  background-color: white;
  border-bottom: 1px solid #eee;
}

.back-button {
  display: flex;
  align-items: center;
  color: #333;
  text-decoration: none;
}

.back-button:hover {
  color: #1890ff;
}

.product-detail-content {
  padding: 20px;
  background-color: white;
}

.loading-container, .error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.product-info {
  display: flex;
  gap: 40px;
}

.product-images {
  flex: 1;
  min-width: 500px;
}

.main-image {
  width: 100%;
  height: 500px;
  background-color: #f9f9f9;
display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  overflow: hidden;
}

.main-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.thumbnail {
  width: 80px;
  height: 80px;
background-color: #f9f9f9;
  cursor: pointer;
  border: 2px solid transparent;
  overflow: hidden;
}

.thumbnail.active {
  border-color: #1890ff;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-basic-info {
  flex: 1;
  min-width: 400px;
}

.product-name {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.product-price {
  margin-bottom: 16px;
}

.price-value {
  font-size: 28px;
  font-weight: 600;
  color: #f56c6c;
}

.product-stock, .product-sales {
  margin-bottom: 12px;
  color: #606266;
}

.product-rating {
  margin-bottom: 16px;
}

.product-specs {
  margin: 20px 0;
}

.specs-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
}

.spec-group {
  margin-bottom: 16px;
}

.spec-name {
  display: block;
  margin-bottom: 8px;
  color: #606266;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-option {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.spec-option:hover {
  border-color: #1890ff;
}

.spec-option.active {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #ecf5ff;
}

.quantity-selector {
  margin: 20px 0;
  display: flex;
  align-items: center;
}

.quantity-label {
  margin-right: 16px;
  color: #606266;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  background-color: white;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.quantity-controls input {
  width: 60px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-left: none;
  border-right: none;
  text-align: center;
  outline: none;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 30px;
}

.action-buttons .el-button {
  flex: 1;
}

.product-detail-tabs {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
}

.product-description {
  line-height: 1.8;
  color: #606266;
}

.reviews-container {
  margin-top: 20px;
}

.review-item {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.reviewer-name {
  font-weight: 600;
  margin-right: 16px;
}

.review-date {
  margin-left: auto;
  color: #909399;
  font-size: 14px;
}

.review-content {
  margin-bottom: 12px;
  line-height: 1.6;
  color: #606266;
}

.review-images {
  display: flex;
  gap: 10px;
}

.review-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.no-reviews {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

.service-info ul {
  padding-left: 20px;
  line-height: 2;
  color: #606266;
}

.related-products {
  margin-top: 20px;
  padding: 20px;
  background-color: white;
}

.related-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.related-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.related-item {
  cursor: pointer;
  transition: all 0.3s;
}

.related-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.related-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  background-color: #f9f9f9;
  margin-bottom: 10px;
}

.related-name {
  font-size: 14px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 8px;
}

.related-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-info {
    gap: 30px;
  }
  
  .product-images {
    min-width: 400px;
  }
  
  .main-image {
    height: 400px;
  }
  
  .product-basic-info {
    min-width: 300px;
  }
  
  .related-list {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 992px) {
  .product-detail-container {
    padding: 15px;
  }
  
  .product-info {
    gap: 20px;
  }
  
  .product-images {
    min-width: 350px;
  }
  
  .main-image {
    height: 350px;
  }
  
  .product-basic-info {
    min-width: auto;
  }
  
  .related-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .product-info {
    flex-direction: column;
    gap: 20px;
  }
  
  .product-images {
    min-width: auto;
  }
  
  .main-image {
    height: 300px;
  }
  
  .product-basic-info {
    min-width: auto;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .quantity-selector {
    width: 100%;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .product-description {
    padding: 15px;
  }
  
  .related-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .product-detail-container {
    padding: 10px;
  }
  
  .product-detail-header {
    padding: 10px 0;
  }
  
  .main-image {
    height: 250px;
  }
  
  .thumbnail-list {
    gap: 5px;
  }
  
  .thumbnail {
    width: 50px;
    height: 50px;
  }
  
  .product-name {
    font-size: 20px;
  }
  
  .price-value {
    font-size: 24px;
  }
  
  .action-buttons .el-button {
    font-size: 14px;
    padding: 10px;
  }
  
  .related-list {
    grid-template-columns: 1fr;
  }
  
  .related-image {
    height: 150px;
  }
}
</style>